package com.learn.concurrent.leetcode.p1116;

public class ZeroEvenOdd {

    private int i = 0;
    Object lock = new Object();

    /**
     * 打印奇数
     */
    private void printZero() {
        while (i<10) {
            System.out.println(Thread.currentThread() + " 打印 0");
        }
    }

    /**
     * 打印偶数
     */
    private void printEven() {
        synchronized (lock) {
            while (i < 10) {
                if (i % 2 == 0 && i != 0) {
                    System.out.println(Thread.currentThread() + " 打印偶数 " + i);
                    i++;
                    lock.notify();

                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 打印奇数
     */
    private void printOdd() {
        synchronized (lock) {
            while (i < 10) {
                if (i % 2 == 1) {
                    System.out.println(Thread.currentThread() + " 打印奇数 " + i);
                    i++;
                    lock.notify();
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //线程A 打印0
    //线程B 打印偶数
    //线程C 打印奇数
    //符合条件的线程运行，不符合条件的线程阻塞

    public static void main(String[] args) {
        ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd();

        /*Thread threadZero = new Thread(new Runnable() {
            @Override
            public void run() {
                zeroEvenOdd.printZero();
            }
        });

        threadZero.start();*/

        new Thread(new Runnable() {
            @Override
            public void run() {
                zeroEvenOdd.printZero();
            }
        },"线程A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                zeroEvenOdd.printEven();
            }
        }, "线程B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                zeroEvenOdd.printOdd();
            }
        }, "线程C").start();
    }

}
